package com.qulai.amazon_us.util.basic;

import com.qulai.amazon_us.domain.amazon_us.AmazonUsRecord;
import com.qulai.amazon_us.domain.basic.Product;
import com.qulai.amazon_us.mapper.amazon_us.AmazonUsRecordMapper;
import com.qulai.amazon_us.mapper.basic.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class BasicUtil {

    @Autowired
    private AmazonUsRecordMapper amazonUsRecordMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 将文件从本地文件夹移动到共享文件夹
     *
     * @param localBasePath  本地基础路径
     * @param sharedBasePath 共享文件夹基础路径
     */
    public static void moveFilesToSharedFolder(String localBasePath, String sharedBasePath) {
        File localBaseDir = new File(localBasePath);
        moveFilesRecursively(localBaseDir, localBasePath, sharedBasePath);
    }

    /**
     * 递归移动文件
     */
    private static void moveFilesRecursively(File currentDir, String localBasePath, String sharedBasePath) {
        if (!currentDir.exists() || !currentDir.isDirectory()) {
            return;
        }

        File[] files = currentDir.listFiles();
        if (files == null) {
            return;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                moveFilesRecursively(file, localBasePath, sharedBasePath);
            } else {
                try {
                    // 计算相对路径
                    String relativePath = file.getParent().substring(localBasePath.length());
                    String destinationDir = sharedBasePath + relativePath;

                    // 确保目标目录存在
                    new File(destinationDir).mkdirs();

                    // 移动文件
                    Path source = file.toPath();
                    Path destination = Paths.get(destinationDir, file.getName());
                    Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    System.err.println("Failed to move file " + file.getAbsolutePath() + ": " + e.getMessage());
                }
            }
        }

        // 如果目录为空，则删除
        if (currentDir.listFiles() != null && Objects.requireNonNull(currentDir.listFiles()).length == 0) {
            currentDir.delete();
        }
    }

    /**
     * 更新亚马逊价格和库存到文本文件
     *
     * @param platform       平台代码
     * @param countThreshold 库存阈值
     */
//    public void updateAmazonPriceQuantityToTxt(String platform, int countThreshold,Map<String, Object> priceStrategyMap) {
//        // 获取当前日期字符串
//        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
//        Map<String, List<List<String>>> taskRecordChange = new HashMap<>();
//        // 需要更新的记录
//        List<AmazonUsRecord> needUpdateRecordDb = new ArrayList<>();
//        LocalDateTime now = LocalDateTime.now();
//
//        // 1. 查询亚马逊记录
//        List<AmazonUsRecord> records = amazonUsRecordMapper.selectRecordsByPlatform(platform);
//
//        if (records != null && !records.isEmpty()) {
//            // 收集所有basic_id
//            List<String> basicIds = records.stream()
//                    .filter(r -> r.getBasicId() != null)
//                    .map(r -> r.getBasicId().toString())
//                    .collect(Collectors.toList());
//
//            if (!basicIds.isEmpty()) {
//                // 2. 获取基础产品信息
//                String basicIdsStr = String.join(",", basicIds);
//                List<Product> basicProducts = productMapper.selectBasicProductsByIds(basicIdsStr);
//
//                // 创建映射以便快速查找
//                Map<String, Integer> basicQuantityMap = new HashMap<>();
//                Map<String, Double> basicPriceMap = new HashMap<>();
//                Map<String, String> classNameMap = new HashMap<>();
//                Map<String, Boolean> deliverLtlMap = new HashMap<>();
//
//                for (Product product : basicProducts) {
//                    if (product.getPublished() == 1 && product.getStatus() == 1) {
//                        basicQuantityMap.put(product.getSku(), product.getQuantity());
//
//                        double price = 0;
//                        if (product.getPrice() != null && product.getShipFee() != null) {
//                            price = Double.parseDouble(product.getPrice()) + Double.parseDouble(product.getShipFee());
//                            price = new BigDecimal(price).setScale(2, RoundingMode.HALF_UP).doubleValue();
//                        }
//                        basicPriceMap.put(product.getSku(), price);
//
//                        classNameMap.put(product.getSku(), product.getClassName());
//
//                        if (product.getExtraField() != null && product.getExtraField().contains("LTL")) {
//                            deliverLtlMap.put(product.getSku(), true);
//                        }
//                    }
//                }
//
//                // 3. 处理每条记录
//                for (AmazonUsRecord record : records) {
//                    String basicSku = record.getBasicSku();
//                    double recordPrice = record.getPrice() != null ? Double.parseDouble(record.getPrice()) : 0;
//                    int recordQuantity = record.getQuantity() != null ? record.getQuantity() : 0;
//
//                    int dbQuantity = basicQuantityMap.getOrDefault(basicSku, 0);
//                    double dbPrice = basicPriceMap.getOrDefault(basicSku, 0.0);
//
//                    String sku = record.getSku();
//                    String shop = record.getShop();
//
//                    // 价格计算策略
//                    double changePrice = getProdPriceByClassName(dbPrice, classNameMap.get(basicSku), priceStrategyMap);
//                    boolean changeStatus = Math.abs(changePrice - recordPrice) > 0.1;
//
//                    LocalDateTime dbTime = LocalDateTime.ofInstant(record.getCreateTime().toInstant(), ZoneId.systemDefault());
//
//                    if (dbPrice == 0 || changeStatus || checkQuantity(recordQuantity, dbQuantity, countThreshold)
//                            || (now.minusDays(1).isBefore(dbTime))) {
//                        String updatePrice = "";
//                        // 这个值超过0.1美元则变化价格
//                        if (dbPrice > 0 && changeStatus) {
//                            updatePrice = String.valueOf(changePrice);
//                        }
//                        int updateQuantity = dbQuantity < countThreshold ? 0 : (int) (dbQuantity * 0.4);
//                        List<List<String>> shopRecord = taskRecordChange.getOrDefault(shop, new ArrayList<>());
//                        String handlingTime = "";
//                        if ("GG".equals(platform)) {
//                            if (basicSku.startsWith("B")) {
//                                handlingTime = "3";
//                            }
//                            if (deliverLtlMap.getOrDefault(basicSku, false)) {
//                                handlingTime = "5";
//                            }
//                        }
//                        List<String> recordData = Arrays.asList(
//                                sku, updatePrice, "", "", String.valueOf(updateQuantity), handlingTime, "");
//                        shopRecord.add(recordData);
//                        taskRecordChange.put(shop, shopRecord);
//                        // 更新记录
//                        AmazonUsRecord updateRecord = new AmazonUsRecord();
//                        updateRecord.setId(record.getId());
//                        updateRecord.setQuantity(dbQuantity);
//                        updateRecord.setPrice(new BigDecimal(changePrice).setScale(2, RoundingMode.HALF_UP).toString());
//                        needUpdateRecordDb.add(updateRecord);
//                    }
//                }
//                // 4. 生成文件
//                if (!taskRecordChange.isEmpty()) {
//                    for (Map.Entry<String, List<List<String>>> entry : taskRecordChange.entrySet()) {
//                        String shop = entry.getKey();
//                        List<List<String>> shopRecords = entry.getValue();
//                        if (!shopRecords.isEmpty()) {
//                            String destFolder = createFolder(shop, dateStr + "-quantity_price");
//                            // 添加表头
//                            List<String> header = Arrays.asList(
//                                    "sku", "price", "minimum-seller-allowed-price",
//                                    "maximum-seller-allowed-price", "quantity",
//                                    "handling-time", "fulfillment-channel");
//                            shopRecords.add(0, header);
//                            // 写入文件
//                            write2DListToTxt(destFolder + File.separator + dateStr + "-" + platform + "_quantity_price.txt",shopRecords);
//                        }
//                    }
//                }
//                // 5. 更新记录表
//                if (!needUpdateRecordDb.isEmpty()) {
//                    amazonUsRecordMapper.batchUpdateQuantityAndPrice(needUpdateRecordDb);
//                }
//            }
//        }
//    }

    /**
     * 获取亚马逊价格策略
     *
     * @return 价格策略映射
     */
    @SuppressWarnings("unchecked")
    private static Map<String, Object> getAmazonUsPriceStrategy() {
        // 这里应该从配置或数据库中获取价格策略
        // 为简化示例，这里直接返回一个硬编码的策略
        Map<String, Object> priceStrategy = new HashMap<>();

        // 固定比例策略示例
        Map<String, Object> fixedRatioStrategy = new HashMap<>();
        fixedRatioStrategy.put("type", "fixed_ratio");
        fixedRatioStrategy.put("formula", "cost/0.7");
        priceStrategy.put("Electronics", fixedRatioStrategy);

        // 分层策略示例
        Map<String, Object> tieredStrategy = new HashMap<>();
        tieredStrategy.put("type", "tiered");

        List<Map<String, Object>> tiers = new ArrayList<>();

        Map<String, Object> tier1 = new HashMap<>();
        tier1.put("min", 0.0);
        tier1.put("max", 20.0);
        tier1.put("formula", "cost/0.65");
        tiers.add(tier1);

        Map<String, Object> tier2 = new HashMap<>();
        tier2.put("min", 20.0);
        tier2.put("max", 50.0);
        tier2.put("formula", "(cost+21)/0.7");
        tiers.add(tier2);

        Map<String, Object> tier3 = new HashMap<>();
        tier3.put("min", 50.0);
        tier3.put("max", Double.MAX_VALUE);
        tier3.put("formula", "cost/0.75");
        tiers.add(tier3);

        tieredStrategy.put("tiers", tiers);
        priceStrategy.put("Furniture", tieredStrategy);

        // 默认策略
        Map<String, Object> defaultStrategy = new HashMap<>();
        defaultStrategy.put("type", "fixed_ratio");
        defaultStrategy.put("formula", "cost/0.68");
        priceStrategy.put("Others", defaultStrategy);

        return priceStrategy;
    }

    /**
     * 将二维列表写入文本文件
     *
     * @param filePath 文件路径
     * @param data     二维数据列表
     */
    public static void write2DListToTxt(String filePath, List<List<String>> data) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (List<String> row : data) {
                writer.write(String.join("\t", row));
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("Error writing to file " + filePath + ": " + e.getMessage());
        }
    }

    /**
     * 创建文件夹
     *
     * @param shop       店铺名称
     * @param folderName 文件夹名称
     * @return 创建的文件夹路径
     */
    public static String createFolder(String shop, String folderName) {
        String userHome = System.getProperty("user.home");
        String basePath = userHome + File.separator + "Desktop" + File.separator + "amazon_file";
        String shopPath = basePath + File.separator + shop;
        String folderPath = shopPath + File.separator + folderName;

        new File(folderPath).mkdirs();
        return folderPath;
    }

    /**
     * 检查库存是否需要更新
     *
     * @param recordQuantity 记录的库存
     * @param dbQuantity     数据库的库存
     * @param threshold      阈值
     * @return 是否需要更新
     */
    public static boolean checkQuantity(int recordQuantity, int dbQuantity, int threshold) {
        if (dbQuantity < threshold && recordQuantity > 0) {
            return true;
        }
        if (dbQuantity >= threshold && recordQuantity < threshold) {
            return true;
        }
        return false;
    }


    /**
     * 随机休眠一段时间
     */
    private void sleepRandomDuration() {
        try {
            Random random = new Random();
            Thread.sleep(random.nextInt(1000) + 1000); // 随机休眠1-2秒
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 根据类名计算产品价格
     */
    public double getProdPriceByClassName(double cost, String className, Map<String, Object> priceStrategy) {
        double calPrice = calculatePrice(cost, className, priceStrategy);
        calPrice = new BigDecimal(calPrice).setScale(2, RoundingMode.HALF_UP).doubleValue();
        double finalPrice = randomPrice(calPrice);
        return finalPrice > 0 ? finalPrice : 0;
    }

    /**
     * 计算价格
     */
    @SuppressWarnings("unchecked")
    private double calculatePrice(double cost, String className, Map<String, Object> priceStrategy) {
        if (!priceStrategy.containsKey(className)) {
            className = "Others";
        }

        Map<String, Object> strategy = (Map<String, Object>) priceStrategy.get(className);
        String type = (String) strategy.get("type");

        if ("fixed_ratio".equals(type)) {
            String formula = (String) strategy.get("formula");
            double denominator = Double.parseDouble(formula.split("/")[1]);
            return cost / denominator;
        } else if ("tiered".equals(type)) {
            List<Map<String, Object>> tiers = (List<Map<String, Object>>) strategy.get("tiers");

            for (Map<String, Object> tier : tiers) {
                double minCost = tier.containsKey("min") ? (double) tier.get("min") : 0;
                double maxCost = tier.containsKey("max") ? (double) tier.get("max") : Double.MAX_VALUE;

                if (minCost <= cost && cost <= maxCost) {
                    String formula = (String) tier.get("formula");

                    if (formula.contains("+")) {
                        // 处理带加法的公式，如 (cost+21)/0.7
                        String[] parts = formula.replace("(", "").replace(")", "").split("/");
                        String[] addParts = parts[0].split("\\+");
                        double addValue = Double.parseDouble(addParts[1]);
                        double denominator = Double.parseDouble(parts[1]);
                        return (cost + addValue) / denominator;
                    } else {
                        // 处理简单除法公式，如 cost/0.63
                        double denominator = Double.parseDouble(formula.split("/")[1]);
                        return cost / denominator;
                    }
                }
            }
        }

        return cost;
    }

    /**
     * 随机价格（增加一点随机性）
     */
    private double randomPrice(double price) {
        // 在原价格基础上增加一点随机性，比如±0.01
        Random random = new Random();
        return price + (random.nextDouble() * 0.02 - 0.01);
    }

    public static String truncateAtQuestionMark(String url) {
        // 检查 null 或空字符串
        if (url == null || url.isEmpty()) {
            return "";
        }
        // 如果包含“?”，只保留“?”前面的部分
        if (url.contains("?")) {
            return url.substring(0, url.indexOf("?"));
        }
        // 否则保持原样
        return url;
    }
}
